package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.dataConfig.ResponseStatus;
import com.dongdongshop.dataConfig.dataResult;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import com.dongdongshop.util.PageBean;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("goods")
public class GoodsController {
    private Logger logger = LoggerFactory.getLogger(GoodsController.class);
    @Reference
    private ItemService itemService;
    @Reference
    private TemplatesService templatesService;
    @Reference
    private GoodsService goodsService;
    @Reference
    private SpecificationOptionService specificationOptionService;



    @RequestMapping("toGoods")
    public String toGoods(){
        return "admin/goods_edit";
    }

    @RequestMapping("editGoods")
    public String editGoods(){
        return "admin/goods";
    }

    @RequestMapping("toget1")
    @ResponseBody
    public dataResult toGet1(Long id){
        try {
            List<TbItemCat> list = itemService.toGet1(id);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),list);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    //获取模板id,查询商品品牌
    @RequestMapping("toGet2")
    @ResponseBody
    public dataResult toGet2(Long id){
        try {
            TbItemCat t = itemService.toGet2(id);
            TbTypeTemplate type = templatesService.toGet2(t.getTypeId());
            String specs = type.getSpecIds();
            //解析模板中的规格信息
            List<specVo> slist = JSONObject.parseArray(specs, specVo.class);
            //循环调用根据规格查询出规格选项并组装数据
            for (specVo spec : slist) {
                List<TbSpecificationOption>  options =  templatesService.listOptionsBySpecId(spec.getId());
                spec.setOptions(options);

            }
            Map<String,Object> map = new HashMap<>();
            map.put("t",t);
            map.put("brand",type);
            map.put("slist",slist);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),map);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("toAdd")
    @ResponseBody
    public dataResult toAdd(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc,Long typeTemplateId,TbItem tbItem,String OptionString){
        try {
            TbSeller  seller= (TbSeller)SecurityUtils.getSubject().getPrincipal();
            tbGoods.setSellerId(seller.getSellerId());
            tbGoods.setTypeTemplateId(typeTemplateId);
            tbGoods.setAuditStatus("0");


            tbItem.setTitle(tbGoodsDesc.getIntroduction());
            tbItem.setCategoryid(typeTemplateId);
            tbItem.setStatus("0");
            tbItem.setCreateTime(new Date());
            tbItem.setUpdateTime(new Date());
            tbItem.setSellerId(seller.getSellerId());
            tbItem.setSeller(seller.getNickName());
            List<GoodsColor> slist = JSONObject.parseArray(tbGoodsDesc.getItemImages(), GoodsColor.class);
            String img = slist.get(0).getUrl();
            tbItem.setImage(img);
            Integer i = goodsService.addinfo(tbGoods,tbGoodsDesc,tbItem,OptionString);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName());
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("getinfo")
    @ResponseBody
    public dataResult getinfo(@RequestParam(defaultValue = "1")Integer number, @RequestParam(defaultValue = "8")Integer pageSize
                              ,String status,String sname){
        try {
            TbSeller  seller= (TbSeller)SecurityUtils.getSubject().getPrincipal();
            String sellerId = seller.getSellerId();
            PageBean<TbGoodsVo> b = goodsService.getinfoSeller(number,pageSize,status,sname,sellerId);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),b);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }


    //将图片上传到阿里云上
    @RequestMapping("uploadFile")
    @ResponseBody
    public dataResult uploadFile (@RequestParam(value = "myFile") MultipartFile myFile){
        try {
            //阿里云上传图片sdk
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-beijing.aliyuncs.com";
            String domain = "oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
            String accessKeyId = "LTAI4GEGkEzP3TXfWZX4uBE1";
            String accessKeySecret = "HMBAjZTWfd2o6SWMs2NoyNDVt9ONAe";
            String bucketName = "lashibudaizhi";
            // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = myFile.getOriginalFilename();

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String content = "Hello OSS";
            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
            // 关闭OSSClient。
            String url = "https://"+bucketName+"."+domain+"/"+objectName;
            ossClient.shutdown();
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),url);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("deleteAll")
    @ResponseBody
    public dataResult deleteAll(@RequestParam("ids[]")Long[] ids){
        try {
            Integer i = goodsService.deleteAll(ids);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName());
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("goGo")
    @ResponseBody
    public dataResult goGo(@RequestParam("ids[]")Long[] ids){
        try {
            Integer i = goodsService.goGo(ids);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName());
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

}
